<script lang="ts">
export default {
  name: 'comHead',
}
</script>
<template>
  <header class="head-box">
    <div class="head-l-box">
      <router-link to="/" :class="{'active': path === '/'}">模特库</router-link>
      <router-link to="/package" :class="{'active': path === '/package'}">套餐</router-link>
    </div>
    <div class="head-r-box">
      <router-link to="/cart" :class="{'active': path === '/cart'}">购物车</router-link>
      <div class="login-btn" v-if="isLogin == false" @click="loginSubmit">登录</div>
      <div v-else>
        <el-dropdown class="user-box">
          <div>
            <el-avatar :size="34" :src="userInfo.avatar"/>
            <div class="name-box">{{ userInfo.nickname }}</div>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>
                <router-link to="/order">
                  <div class="user-box-item">
                    <img src="./../../assets/images/order.png" alt="订单">
                    <span>我的订单</span>
                  </div>
                </router-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <router-link to="/wallet">
                  <div class="user-box-item">
                    <img src="./../../assets/images/money.png" alt="财务">
                    <span>财务管理</span>
                  </div>
                </router-link>
              </el-dropdown-item>
              <!--<el-dropdown-item>-->
              <!--  <router-link to="/user">-->
              <!--    <div class="user-box-item">-->
              <!--      <img src="./../../assets/images/user.png" alt="">-->
              <!--      <span>个人中心</span>-->
              <!--    </div>-->
              <!--  </router-link>-->
              <!--</el-dropdown-item>-->
              <el-dropdown-item divided>
                <div class="user-box-item" @click="logOut()">
                  <img src="./../../assets/images/exit.png" alt="">
                  <span>退出登录</span>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>


        <!--{{userInfo}}-->
      </div>
    </div>
  </header>

  <el-dialog
      v-model="loginDialog"
      :show-header="false"
      :before-close="stopGetFn"
      style="border-radius: 12px; padding: 20px;"
      width="420"
  >
    <div class="login-dialog">
      <h2 class="title-box">手机扫码 快速登录</h2>
      <div class="title-tip">使用微信扫一扫&nbsp;1秒即可登录</div>
      <div class="img-box">
        <img :src="qrCodeUrl" alt="">
      </div>
      <div class="xy-box">
        <span>注册登录即代表同意</span>
        <span class="xy-text">《用户协议》</span>
        <span> 和 </span>
        <span class="xy-text">《隐私协议》</span>
      </div>
    </div>
  </el-dialog>

</template>
<script lang="ts" setup>
import {useRoute} from "vue-router";
import Https from "@/server";
import {onMounted, ref, watch} from "vue";
import QRCode from 'qrcode';

const Route = useRoute()
const path = ref("/");

const loginDialog = ref(false);
const qrCodeUrl = ref('');
const state = ref('');
const countNum = ref(0);
const isLogin = ref(false);
const userInfo = ref({
  avatar: "",
  nickname: "",
});

const loginSubmit = () => {
  loginDialog.value = true;
  let item = Https.getLoginCode().then(res => {
    state.value = res as string;
  })
  Promise.all([item]).then(() => {
    generateQRCode();
  })

  let ct = setTimeout(() => {
    userStatus();
    clearTimeout(ct);
  }, 3000)
}

const stopGetFn = () => {
  countNum.value = 100;
  loginDialog.value = false;
}

const userStatus = () => {
  countNum.value += 1;
  if (countNum.value < 100) {
    Https.getUserLoginStatus(state.value).then((res: any) => {
      // console.log(res);
      if (res.data == null) {
        let ct = setTimeout(() => {
          userStatus();
          clearTimeout(ct);
        }, 3000)
      } else {
        if(res.data.username == "微信用户"){
          let ct = setTimeout(() => {
            userStatus();
            clearTimeout(ct);
          }, 3000)
        } else {
          localStorage.setItem("access_token", res.data.access_token);
          window.location.reload();
          loginDialog.value = false;
        }
      }
    })
  } else {
    loginDialog.value = false;
  }

}


// 生成二维码方法
const generateQRCode = async () => {
  // d5cb9096d81dbbea4dc983f0aab71d58
  let appId = 'wxc9d62b3182027f56';
  let redirectUri = encodeURIComponent('https://xiaohutiger.cn/login'); // 回调地址
  // let redirectUri = encodeURIComponent('https://wwhome.com.cn/login'); // 回调地址
  let scope = 'snsapi_userinfo';
  let data = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state.value}#wechat_redirect`
  console.log(data)
  try {
    countNum.value = 0;
    qrCodeUrl.value = await QRCode.toDataURL(data, {
      width: 180,
      margin: 2,
      color: {
        dark: '#000000ff',
        light: '#ffffffff'
      }
    })
  } catch (err) {
    console.error('生成二维码失败:', err)
  }

}

// 退出登录
const logOut = () => {
  localStorage.clear();
  window.location.reload();
}

const userInfoData = () => {
  Https.getUserInfo().then((res: any) => {
    // console.log(res);
    if (res.code == 0) {
      userInfo.value = res.data;
      localStorage.setItem("userInfo", JSON.stringify(res.data));
      isLogin.value = true;
    } else {
      isLogin.value = false;
    }
  })
}

onMounted(() => {
  userInfo.value = JSON.parse(localStorage.getItem("userInfo") as string);
  if (userInfo.value) {
    isLogin.value = true;
  } else {
    userInfoData();
  }

  // userInfo.value = JSON.parse(localStorage.getItem("userInfo") as string);
})

watch(
    () => Route.path,
    (newPath) => {
      path.value = newPath;
    }
)

</script>
<style scoped lang="scss">
.head-box {
  height: 60px;
  align-items: center;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;

  div {
    display: flex;
  }
}

.head-l-box {
  a {
    padding-right: 20px;
    font-size: 15px;
    cursor: pointer;
  }

  a:hover {
    color: var(--el-color-primary);;
  }

  a.active {
    color: var(--el-color-primary);
  }
}

.head-r-box {
  font-size: 15px;
  align-items: center;

  a {
    padding-right: 24px;
    border-right: 1px solid #5555558a;
    margin-right: 24px;
    height: 20px;
    line-height: 20px;
  }

  a:hover {
    color: var(--el-color-primary);;
  }

  a.active {
    color: var(--el-color-primary);
  }
}

.login-btn {
  padding-right: 20px;
  cursor: pointer;
}

.login-btn:hover {
  color: var(--el-color-primary);;
}

.login-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;

  .title-box {
    text-align: center;
    color: var(--text-color);
    padding: 0;
    margin: 0;
  }

  .title-tip {
    margin-bottom: 22px;
  }

  .img-box {
    width: 180px;
    height: 180px;
    //background-color: #2c3e50;
  }

  .xy-box {
    margin-top: 32px;
    color: var(--el-color-info);
    font-size: 12px;

    .xy-text {
      color: var(--el-color-primary);
    }
  }

}

.user-box {
  cursor: pointer;
}

.name-box {
  padding-left: 8px;
  height: 34px;
  line-height: 34px;

}

.user-box-item {
  height: 24px;
  display: flex;
  align-items: center;
  padding: 0 10px;

  img {
    width: 18px;
    height: 18px;
  }

  span {
    padding-left: 10px;
    font-size: 12px;
    color: #647484;
  }
}

</style>